﻿using Abp.Data;
using Abp.Domain.Entities;
using Abp.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using JYJ.AiYard.EntityFrameworkCore.Repositories;

namespace JYJ.AiYard.EntityFrameworkCore.Repositories
{
  
    public abstract class RepositoryAndSqlHelper<TEntity, TPrimaryKey> : AiYardRepositoryBase<TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey>
    {
        private readonly IActiveTransactionProvider _transactionProvider;
        //private readonly IDbContextProvider<AiYardDbContext> _dbContextProvider;

        protected RepositoryAndSqlHelper(IDbContextProvider<AiYardDbContext> dbContextProvider, IActiveTransactionProvider transactionProvider)
            : base(dbContextProvider)
        {
            _transactionProvider = transactionProvider;
           // _dbContextProvider = dbContextProvider;
        }

        public DbCommand CreateCommand(string commandText, CommandType commandType, params SqlParameter[] parameters)
        {
            EnsureConnectionOpen();
            var command = Context.Database.GetDbConnection().CreateCommand();
            command.CommandText = commandText;
            command.CommandType = commandType;
            command.Transaction = GetActiveTransaction();

            foreach (var parameter in parameters)
            {
                command.Parameters.Add(parameter);
            }

            return command;
        }
       

        private void EnsureConnectionOpen()
        {
            var connection = Context.Database.GetDbConnection();
            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
        }

       
        private DbTransaction GetActiveTransaction()
        {
            return (DbTransaction)_transactionProvider.GetActiveTransaction(new ActiveTransactionProviderArgs
            {
                {"ContextType", typeof(AiYardDbContext) },
                {"MultiTenancySide", MultiTenancySide }
            });
        }
    }
}

